import { DetailVO, saveRes } from '../services';
import { Dialog, Field, Form, Icon, Input, NumberPicker, Select, Switch } from '@alifd/next';
import { ResourceTypeEnums } from '@/pages/BaseManage/ResourceManage/entity';
import { useEffect } from 'react';
import { useRequest } from 'ice';
import { EnableStatus } from '@/common/entity';

interface Props {
  visible?: boolean;
  onClose?: () => any;
  onRefresh?: () => any;
  record?: DetailVO;
  parentId?: number;
}

const { Item: FormItem } = Form;

const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 10,
  },
};

function EditDialog({ visible, onClose, record, parentId, onRefresh }: Props) {
  const form = Field.useField([{}]);
  const { loading, request } = useRequest<string, DetailVO[]>(saveRes, {
    defaultParams: [{}],
    debounceInterval: 300,
    onSuccess: () => {
      onClose?.();
      onRefresh?.();
    },
  });

  useEffect(() => {
    if (visible) {
      let fromValues = {
        parentId,
        status: true,
      };
      if (record) {
        fromValues = {
          ...record,
          status: record?.status == EnableStatus.ENABLE,
          parentId,
        };
      }
      form.setValues(fromValues);
    }
  }, [visible]);

  const onSubmit = () => {
    form.validateCallback((errors: any[], values: any) => {
      if (errors) {
        return;
      }
      request({ ...values, status: values.status ? 1 : 0, id: record?.id });
    });
  };

  return (
    <Dialog
      title={record?.id ? '编辑资源' : '新增资源'}
      v2
      visible={visible}
      overflowScroll
      width="50%"
      onOk={onSubmit}
      onClose={onClose}
      afterClose={() => form.reset()}
      okProps={{ loading }}
    >
      <Form {...formItemLayout} disabled={loading} field={form} fullWidth colon useLabelForErrorMessage>
        <FormItem name="parentId" label="parentId" style={{ display: 'none' }}>
          <Input />
        </FormItem>
        <FormItem name="name" label="名称" required>
          <Input />
        </FormItem>
        <Form.Item label="资源类型" required>
          <Select name="type" placeholder="请选择" hasClear dataSource={ResourceTypeEnums} />
        </Form.Item>
        <FormItem name="uri" label="资源路径" required>
          <Input />
        </FormItem>
        <FormItem name="status" label="状态">
          <Switch autoWidth size="small" checkedChildren="启用" unCheckedChildren="禁用" />
        </FormItem>
        <FormItem name="sort" label="排序" min={0}>
          <NumberPicker defaultValue={0} />
        </FormItem>
        <FormItem name="icon" label="图标">
          <Input innerAfter={<Icon type={form.getValue('icon')} style={{ marginRight: 10 }} />} />
        </FormItem>
        <FormItem label="备注" name="remark">
          <Input.TextArea />
        </FormItem>
      </Form>
    </Dialog>
  );
}

export default EditDialog;
